package com.ruoyi.socket.controller;

import com.alibaba.fastjson.JSON;
import com.ruoyi.socket.domain.TbAnswer;
import com.ruoyi.socket.entity.WechatResponse;
import com.thoughtworks.xstream.XStream;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.mockito.stubbing.Answer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 晓彬
 * @date 2023-05-07 19:58
 */
@RestController
@RequestMapping("/wechat")
public class WeChatController {

    /**
     * 内网穿透链接
     * @param signature
     * @param timestamp
     * @param nonce
     * @param echostr
     * @return
     */
    @GetMapping("/message")
    public String initWechat(String signature, String timestamp, String nonce, String echostr) {
        System.out.println(signature + "-" + timestamp + "-" + nonce + "-" + echostr);
        return echostr;

    }

    @Autowired
    private RestHighLevelClient restHighLevelClient;
    /**
     * 微信公众号测试
     * @param request
     * @return
     * @throws IOException
     * @throws DocumentException
     */
    @PostMapping("/message")
    public String message(HttpServletRequest request) throws IOException, DocumentException {
        ServletInputStream inputStream = request.getInputStream();

        //创建对象读取报文
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(inputStream);
        Map<String,String> requestXML=new HashMap();
        //获取报文根元素
        Element rootElement = document.getRootElement();
        //获取所有子元素
        List<Element> elements = rootElement.elements();
        for (Element child : elements) {
            requestXML.put(child.getName(),child.getStringValue());

        }

        System.out.println(requestXML);
        //获取存入到map中,微信发过来的
        String message = requestXML.get("Content");


        //根据message的数据,查询es的常见问题,返回
        SearchRequest searchRequest = new SearchRequest("answer");
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        queryBuilder.must(QueryBuilders.matchQuery("antistop", message));
        searchRequest.source().query(queryBuilder);
        SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        SearchHit[] hits = response.getHits().getHits();
        String result="";
        if(hits.length==0){

            result="您的消息已经收到,请等待客服联系";
        }else{
          for (int i=0;i<hits.length;i++){
              String sourceAsString = hits[i].getSourceAsString();
              TbAnswer answer = JSON.parseObject(sourceAsString, TbAnswer.class);
             result+=(i+1)+":"+ answer.getAnswerResult();

          }
        }

        //封装对象
        WechatResponse wechatResponse = new WechatResponse();
        wechatResponse.setContent(result);
        wechatResponse.setMsgType("text");
        wechatResponse.setCreateTime(System.currentTimeMillis()+"");
        wechatResponse.setFromUserName(requestXML.get("ToUserName"));
        wechatResponse.setToUserName(requestXML.get("FromUserName"));
        //生成报文
        XStream xStream = new XStream();
        xStream.alias("xml", WechatResponse.class);
        String responseXML = xStream.toXML(wechatResponse).toString();
        System.out.println(responseXML);
        return responseXML;


    }


}